package com.lin.fengxiu.repository;

import com.lin.fengxiu.model.Order;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.Date;
import java.util.Optional;

/**
 * @ClassName OrderRepository
 * @Description TODO 订单ORM
 * @Author wushaopei
 * @Date 2021/4/7 11:09
 * @Version 1.0
 */
public interface OrderRepository extends JpaRepository<Order, Long> {

    /**
     * @Description TODO 根据status和expiredTime查询未支付订单
     * @param now 当前时间
     * @param status 订单状态
     * @param uid   用户id
     * @param pageable  分页模型
     */
    Page<Order> findByExpiredTimeGreaterThanAndStatusAndUserId(Date now, Integer status, Long uid, Pageable pageable);


    /**
     * @Description TODO 查询所有的订单
     * @param uid
     * @param pageable
     * @return
     */
    Page<Order> findByUserId(Long uid, Pageable pageable);

    /**
     * @Description TODO 根据status 查询订单
     * @param uid
     * @param status
     * @param pageable
     * @return
     */
    Page<Order> findByUserIdAndStatus(Long uid, Integer status, Pageable pageable);


    /**
     * @Description TODO 查询订单详情
     * @param uid
     * @param oid
     * @return
     */
    Optional<Order> findFirstByUserIdAndId(Long uid, Long oid);

    /**
     * @Description TODO 根据订单号查询订单
     * @param orderNo
     * @return
     */
    Optional<Order> findFirstByOrderNo(String orderNo);

    /**
     * @Description TODO 订单支付成功，更新订单状态为 PAID
     * @param orderNo
     * @param status
     * @return
     */
    @Modifying
    @Query("update Order o set o.status = :status where o.orderNo = :orderNo")
    int updateStatusByOrderNo(String orderNo, Integer status);

    @Modifying
    @Query("update Order o set o.status=5 where o.status = 1 and o.id=:oid")
    int cancelOrder(Long oid);
}
